/*
 * 上海远境文化传媒有限公司 版权所有
 */
package models.base;

import facade.AppContext;
import facade.vo.base.RoleBusinessVO;
import helper.GlobalConfig;
import models.common.BaseModel;
import models.constants.DeletedStatus;
import models.enums.AvailableStatus;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.modules.paginate.JPAExtPaginator;

import javax.persistence.*;
import java.util.*;

/**
 * 角色身份管理.
 */
@Entity
@Table(name = "admin_roles", schema = GlobalConfig.MIGAO_DB_SCHEMA)
public class Role extends BaseModel {

    /**
     * 角色名.
     */
    @Column(name = "name", length = 50)
    public String name;

    /**
     * 备注.
     */
    @Column(name = "remark", length = 500)
    public String remark;

    /**
     * 显示顺序.
     */
    @Column(name = "show_order", columnDefinition = "integer")
    public Integer showOrder;

    /**
     * 状态，0 - 可用、1 - 禁用
     */
    @Enumerated(EnumType.ORDINAL)
    @Column(name = "status")
    public AvailableStatus status = AvailableStatus.AVAILABLE;


    public static JPAExtPaginator<Role> findByCondition(Map<String, Object> conditionMap, String orderByExpress, int pageNumber, int pageSize) {
        StringBuilder xsqlBuilder = new StringBuilder(" t.deleted = models.constants.DeletedStatus.UN_DELETED ")
                .append("/~ and t.name like {key} ~/")
                .append("/~ and t.corp.id = {corpId} ~/")
                .append("/~ and t.id = {id} ~/");
        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        JPAExtPaginator rolePage = new JPAExtPaginator("Role t" , "t" , Role.class , result.getXsql() , conditionMap).orderBy(orderByExpress);

        Logger.info("-----------------------result :%s" ,result.getXsql() );
        rolePage.setPageNumber(pageNumber);
        rolePage.setPageSize(pageSize);
        rolePage.setBoundaryControlsEnabled(false);
        return rolePage ;

    }


    public static List<Role> findAvailable() {
        return find(" deleted=?1 and status=?2 order by showOrder", DeletedStatus.UN_DELETED, AvailableStatus.AVAILABLE).fetch();
    }
    public static List<Role> findByCorp(Corp corp) {
        return find("corp=?1 and deleted=?2 order by showOrder", corp, DeletedStatus.UN_DELETED).fetch();
    }


    public static Role findByCorpAndId(Corp corp, String id) {
        if(corp == null)
            return find("id=?1 and deleted=?2" , id , DeletedStatus.UN_DELETED).first();
        return find("corp=?1 and id=?2 and deleted=?3", corp, id, DeletedStatus.UN_DELETED).first();
    }
    public static Role findOne(String id) {
        if(StringUtils.isEmpty(id)) return null;
        return find("id=?1 and deleted=?2" , id , DeletedStatus.UN_DELETED).first();
    }

    public static Role findByIdAndStatus(String id,AvailableStatus status) {
        return find("id=?1 and deleted=?2 and status = ?3", id, DeletedStatus.UN_DELETED,status).first();
    }

    /***********************以上为新建********************************/


    public static Role update(String id, Role form) {
        AdminUser loginUser = AppContext.currentUser();
        Role targetRole = Role.findById(id);
        targetRole.name = form.name;
        targetRole.remark = form.remark;
        targetRole.modifyAt = new Date();
        targetRole.modifyUser = loginUser;
        targetRole.save();
        return targetRole;
    }


    /**
     * 改变顺序.
     *
     * @param corp      指定公司
     * @param id        目标ID
     * @param showOrder 目标序号
     */
    public static void changeSortOrder(Corp corp, String id, Integer showOrder) {
        Role currentRole = Role.findByCorpAndId(corp, id);

        if (currentRole == null) {
            return;
        }

        List<Role> roles = findByCorp(corp);
        for (int i = 1; i < roles.size() + 1; i++) {
            Role dept = roles.get(i - 1);
            dept.showOrder = (i >= showOrder) ? (i + 1) : i;
            dept.save();
        }
        currentRole.showOrder = showOrder;
        currentRole.save();
    }

    @Override
    public Role delete() {
        AdminUser loginUser = AppContext.currentUser();
        if (this.deleted == DeletedStatus.UN_DELETED) {
            this.deleted = DeletedStatus.DELETED;
            this.modifyUser = loginUser;
            this.modifyAt = new Date();
            this.save();
        }
        return this;
    }

    public static Set<String> loadRoles(AdminUser user){
        if(user == null) return null;
        Set<String> _set = new HashSet<>();
        if(user.isSuperAdmin || user.isDiySuperAdmin()) {
            _set.add("SuperAdmin");
        }
        if(user.isAdmin!=null && user.isAdmin){
            _set.add("Admin");
        }
        AdminUserRole userRole = AdminUserRole.findByUserId(user.getId());
        if(userRole != null){
            List<RoleBusinessVO> businessList = AdminBusiness.findByRoleId(userRole.role.getId());
            if(businessList != null && businessList.size()>0){
                for (RoleBusinessVO roleBusinessVO : businessList) {
                    if(roleBusinessVO.isSearch != null && roleBusinessVO.isSearch) {
                        _set.add(roleBusinessVO.code + ".search");
                        if (roleBusinessVO.isAdd != null && roleBusinessVO.isAdd) {
                            _set.add(roleBusinessVO.code + ".add");
                        }
                        if (roleBusinessVO.isEdit != null && roleBusinessVO.isEdit) {
                            _set.add(roleBusinessVO.code + ".edit");
                        }
                        if (roleBusinessVO.isDelete != null && roleBusinessVO.isDelete) {
                            _set.add(roleBusinessVO.code + ".delete");
                        }
                    }
                }
            }
        }
        return _set;
    }

    /**
     * 缓存baseKey.
     */
    public static String baseCacheKey(String corpId) {
        return "ROLECORP_" + corpId;
    }


}
